<template>
  <div class="app-container">
    <div>
      <div
        :class="{ fullscreen: fullscreen }"
        class="tinymce-container editor-container"
      >
        <textarea id="tinymceId" class="tinymce-textarea" />
        <div class="editor-custom-btn-container">
          <editorImage
            color="#1890ff"
            class="editor-upload-btn"
            @successCBK="imageSuccessCBK"
          />
        </div>
      </div>
    </div>
    <el-button
      icon="el-icon-info"
      size="mini"
      type="primary"
      @click="addInfo"
      >提交
    </el-button>
    <el-button
      icon="el-icon-check"
      size="mini"
      type="primary"
      @click="getInfo"
      >获取
    </el-button>
  </div>
</template>
<script src=/tinymce4.7.5/tinymce.min.js></script>
<script>
import {
  listText2,
  getText2,
  delText2,
  addText2,
  updateText2,
} from "@/api/pms/text2";
import editorImage from "@/components/Tinymce";
import plugins from "@/components/editContainer/plugins";
import toolbar from "@/components/editContainer/toolbar";
import { getApiUrl } from "@/utils/utils";

export default {
  name: "Text2",
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function () {
        return (
          "vue-tinymce-" +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + "")
        );
      },
    },
    value: {
      type: String,
      default: "",
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [];
      },
    },
    menubar: {
      type: String,
      default: "file edit insert view format table",
    },
    height: {
      type: Number,
      required: false,
      default: 360,
    },
  },
  data() {
    return {
      spec: "one",
      specs: [],
      specDialogFormVisible: false,
      skuForm: {},
      attrKeySel: "",
      attrKeyList: [],
      attrValList: [],
      showAddAttrKey: false,
      attrKeyForm: { attrName: "" },
      attrValForm: { attrVal: "" },
      attrValSel: "",
      attrValListSel: [],
      tags: [],
      form: {
        pic: "",
        gallery: [],
        idCategory: "",
        isHot: false,
        isNew: false,
      },
      skuList: [],
      uploadUrl: "",
      uploadFileId: "",
      uploadHeaders: {
        Authorization: "",
      },
      idGoods: "",
      active: 0,
      categories: [],
      tinymceId: "tinymceId",
      fullscreen: false,
      languageTypeList: {
        en: "en",
        zh: "zh_CN",
      },
      galleryList: [],
      apiUrl: getApiUrl(),
    };
  },
  created() {},
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || "")
        );
      }
    },
    language() {
      this.destroyTinymce();
      this.$nextTick(() => this.initTinymce());
    },
  },
  mounted() {
    this.init();
    this.initTinymce();
  },
  activated() {
    this.initTinymce();
  },
  deactivated() {
    this.destroyTinymce();
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    addInfo(){
      const dcontent = escape(this.getContent());
      //console.log(dcontent);
      addText2({detail:dcontent}).then(response => {
              this.$modal.msgSuccess("添加成功");
            });
    },
    getInfo(){
      getText2(2).then(response => {
            this.setContent(unescape(response.data.detail));
       });
    },
    init() {
      this.uploadUrl = getApiUrl() + "/file";
    },

    initTinymce() {
      const _this = this;
      window.tinymce.init({
        value: "",
        language: "zh_CN",
        selector: `#${this.tinymceId}`,
        height: this.height,
        body_class: "panel-body ",
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: "clean",
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square",
        advlist_number_styles: "default",
        imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        default_link_target: "_blank",
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: (editor) => {
          if (_this.value) {
            editor.setContent(_this.value);
          }
          _this.hasInit = true;
          editor.on("NodeChange Change KeyUp SetContent", () => {
            this.hasChange = true;
            const content = editor.getContent();
            this.form.content = content;
          });
        },
        setup(editor) {
          editor.on("FullscreenStateChanged", (e) => {
            _this.fullscreen = e.state;
          });
        },
      });
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId);
      if (this.fullscreen) {
        tinymce.execCommand("mceFullScreen");
      }

      if (tinymce) {
        tinymce.destroy();
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    getContent() {
      return window.tinymce.get(this.tinymceId).getContent();
    },
    imageSuccessCBK(arr) {
      //console.log(arr)
      const _this = this;
      arr.forEach((v) => {
        //console.log(`<img class="wscnph" src="${v}" >`);
        window.tinymce
          .get(_this.tinymceId)
          .insertContent(`<img class="wscnph" src="${v}" >`);
      });
    },
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const content = this.form.content.split("%").join("%25");
          articelApi
            .save({
              id: this.form.id,
              title: this.form.title,
              author: this.form.author,
              idChannel: this.form.idChannel,
              content: content,
              img: this.form.img,
            })
            .then((response) => {
              this.$message({
                message: this.$t("common.optionSuccess"),
                type: "success",
              });
              this.back();
            });
        } else {
          return false;
        }
      });
    },
    back() {
      this.$router.go(-1);
    },

    handleBeforeUpload() {
      if (this.uploadFileId !== "") {
        this.$message({
          message: this.$t("common.mustSelectOne"),
          type: "warning",
        });
        return false;
      }
      this.loadingInstance = Loading.service({
        lock: true,
        text: this.$t("common.uploading"),
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    handleUploadSuccess(response, raw) {
      this.loadingInstance.close();
      if (response.code === 20000) {
        this.form.img = response.data.realFileName;
      } else {
        this.$message({
          message: this.$t("common.uploadError"),
          type: "error",
        });
      }
    },
    uploadImg() {
      this.ifUpload = !this.ifUpload;
    },
  },
};
</script>
<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container >>> .mce-fullscreen {
  z-index: 10000;
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}

.add_attr_key_row {
  height: 0;
  overflow: hidden;
  transition: all 400ms;
}

.showEdit {
  height: 185px;
}

.add_attr_key_button {
  text-align: center;
  line-height: 40px;
  transition: all 400ms;
}
</style>